package shop.controller;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.pojo.Supplier;
import shop.pojo.SysRole;
import shop.pojo.SysUser;
import shop.service.SysSupplierService;
import shop.utils.Constants;
import shop.utils.OssUtil;
import shop.utils.PageSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/supplier")
public class SysSupplierController {
    @Autowired
    SysSupplierService sysSupplierService;


    //供货商列表
    @RequestMapping("/list")
    public String getUserList(Model model, String querySupCode, String querySupName, @RequestParam(defaultValue = "1") Integer pageIndex){
        List<Supplier> supplierList=null;
        try {
            //设置页面展示条数
            int pageSize = Constants.pageSize;
            System.out.println(pageSize+"展示条数");
            //总条数量
            Integer totalCount =sysSupplierService.getSupplierCount(querySupCode,querySupName);
            //总页数
            PageSupport pages =new PageSupport();
            pages.setTotalCount(totalCount);
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            int totalPageCount =pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex>totalPageCount){
                pageIndex=totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            supplierList=sysSupplierService.getSupplierList(querySupCode,querySupName,pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
            List<SysRole> roleList=null;
            //roleList=sysSupplierService.getSupplierList();
            model.addAttribute("roleList",roleList);
            System.out.println(roleList);
            model.addAttribute("querySupCode",querySupCode);

            model.addAttribute("querySupName",querySupName);

            model.addAttribute("totalPageCount",totalPageCount);
            System.out.println(totalPageCount);
            model.addAttribute("totalCount",totalCount);
            System.out.println(totalCount);
            model.addAttribute("currentPageNo",pageIndex);
            System.out.println(pageIndex);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "supplier/list";
    }

    //查询用户详细
    @GetMapping("/view/{supId}")
    public String userView(@PathVariable Integer supId, Model model){
        Supplier supplier = sysSupplierService.getSupplierDetail(supId);
        model.addAttribute(supplier);
        return "supplier/view";
    }

    //去修改页面
    @GetMapping("/toUpdate/{supId}")
    public String toUpdate(@PathVariable Integer supId,Model model){
        Supplier supplier = sysSupplierService.getSupplierDetail(supId);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    //修改
    @RequestMapping("/update")
    public String toUserUpdate(Supplier supplier, HttpSession session,HttpServletRequest request){
        supplier.setUpdateduserid( ((SysUser)session.getAttribute(Constants.USER_SESSION)).getId() );
        if(request.getParameter("createdtime")==""||request.getParameter("createdtime")==null){
            supplier.setCreatedtime(new Date());
        }
        if(sysSupplierService.update(supplier)>0){
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }

    @GetMapping("/delete")
    public ResponseEntity<Map<String, String>> deleteUser(@RequestParam("method") String method,
                                                          @RequestParam("supId") Integer supId) {
        Map<String, String> responseMap = new HashMap<>();

        System.out.println(method);
        System.out.println(supId);
        if ("deleteById".equals(method)) {

            // 检查用户是否存在
            if (sysSupplierService.supplierExistsById(supId)) {
                // 删除用户
                Integer isDeleted = sysSupplierService.deleteSupplierById(supId);
                if (isDeleted>0) {
                    responseMap.put("delResult", "true");
                } else {
                    responseMap.put("delResult", "false"); // 假设这里表示发生了某种错误，而不是用户不存在
                }
            } else {
                responseMap.put("delResult", "notexist");
            }
        } else {
            // 未知的方法，返回错误
            responseMap.put("delResult", "unknown_method");
        }
        return new ResponseEntity<>(responseMap, HttpStatus.OK);
    }

    @GetMapping("/toAdd")
    public String toAdd(HttpServletRequest request){
        return "supplier/add";
    }


    //用户添加
    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session,Model model,HttpServletRequest request
            ,@RequestParam(value = "companyLicPic",required = false) MultipartFile companyLicPic
            ,@RequestParam(value = "orgCodePic",required = false) MultipartFile orgCodePic
    ) throws IOException {
        System.out.println("111111111111111111111111111111111111");
        SysUser create =(SysUser) session.getAttribute(Constants.USER_SESSION);
        System.out.println(create);
        supplier.setCompanylicpicpath(OssUtil.upload(companyLicPic.getOriginalFilename(),companyLicPic.getInputStream()));
        supplier.setOrgcodepicpath(OssUtil.upload(orgCodePic.getOriginalFilename(),orgCodePic.getInputStream()));
        System.out.println(OssUtil.upload(orgCodePic.getOriginalFilename(),orgCodePic.getInputStream()));
        supplier.setUpdateduserid(create.getId());
        supplier.setSupcode(request.getParameter("supCode"));
        supplier.setSupname(request.getParameter("supName"));
        supplier.setSupcontact(request.getParameter("supContact"));
        supplier.setSupphone(request.getParameter("supPhone"));
        supplier.setSupaddress(request.getParameter("supAddress"));
        supplier.setSupfax(request.getParameter("supFax"));
        supplier.setSupdesc(request.getParameter("supDesc"));
        supplier.setCreatedtime(new Date());
        if(sysSupplierService.add(supplier)){
            return "redirect:/supplier/list";
        }else {
            return "supplier/add";
        }

    }
    
    @GetMapping("/simpleList")
    @CrossOrigin
    @ResponseBody
    public List<Supplier> simpleList(){
        List<Supplier> suppliers = sysSupplierService.getSupnameAndId();
        return suppliers;
    }



}
